<template>
  <view>
    <view class="headerClass">
      <view class="uni-padding-wrap uni-common-mt">
        <uni-segmented-control
          :current="current"
          :values="items"
          :style-type="styleType"
          :active-color="activeColor"
          @clickItem="onClickItem"
        />
      </view>

      <text class="positionClass" @click="xuanzhe">
        <text class="iconfont icon-sousuo" @click="handleSearch"></text>
        <text @click="showHide = !showHide">
          <text class="iconfont icon-jiahao" style="font-size: 40rpx"></text>
        </text>
      </text>
    </view>

    <view class="posiBox" v-show="showHide">
      <view class="common" style="margin-bottom: 10rpx" @click="handleAddLogin"
        >新增登记</view
      >
      <view class="common" @click="handleApplication">申请转运</view>
    </view>
    <view>
      <view v-if="current === 0">
        <view class="boxTitle">
          <view>
            <text
              class="titleClass"
              :class="{ activeClass: titleName == '我的待办' }"
              @click="titleName = '我的待办'"
              >我的待办</text
            >
            <text class="yuanClass">{{ state.rows.length }}</text>
          </view>
          <view style="display: flex; align-items: center">
            <text
              class="titleClass"
              :class="{ activeClass: titleName == '我的已办' }"
              @click="titleName = '我的已办'"
              >我的已办</text
            >
            <!-- <text class="yuanClass">{{ completedObj.rows.length }}</text> -->
          </view>
        </view>
        <view v-show="titleName == '我的待办'">
          <view
            class="overClass"
            v-if="state.rows.length"
            style="max-height: 85vh"
          >
            <view v-for="item in state.rows" :key="item.id">
              <view class="wrapBox">
                <view class="smallBox">
                  <text class="maxwidth">
                    危废行业俗称:{{ item.wfTypeName }}
                  </text>
                </view>
                <view class="smallBox">
                  <text> 部门:{{ item.deptName }} </text>
                  <text> 转运日期:{{ item.planTransTime }} </text>
                </view>
                <view class="smallBox">
                  <text> 申请日期:{{ item.submit_Time }} </text>
                  <text> 申请人:{{ item.userName }} </text>
                </view>
                <view class="smallBox">
                  <text> 当前环节:{{ item.activityName }} </text>
                  <view style="display: flex">
                    <button @click="handleshenpi(item)" class="commonBtnClass">
                      审批
                    </button>
                    <button
                      @click="handleEdit(item)"
                      class="commonBtnClass"
                      v-if="item.activityName == '提交申请'"
                    >
                      编辑
                    </button>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view v-if="!state.rows.length" class="loadingClass">暂无数据</view>
        </view>
        <view v-show="titleName == '我的已办'">
          <view
            class="overClass"
            v-if="completedObj.rows.length"
            style="max-height: 85vh"
          >
            <view v-for="item in completedObj.rows" :key="item.id">
              <view class="wrapBox">
                <view class="smallBox">
                  <text class="maxwidth">
                    危废行业俗称:{{ item.wfTypeName }}
                  </text>
                </view>
                <view class="smallBox">
                  <text> 部门:{{ item.deptName }} </text>
                  <text> 转运日期:{{ item.planTransTime }} </text>
                </view>
                <view class="smallBox">
                  <text> 申请日期:{{ item.submit_Time }} </text>
                  <text> 申请人:{{ item.userName }} </text>
                </view>
                <!-- <view class="smallBox">
                  <text> 当前环节:{{ item.nextActivity }} </text>
                  <text> 当前办理人:{{ item.handleUserName }} </text>
                </view> -->
                <view class="smallBox">
                  <text> 环节:{{ item.activityName }} </text>
                  <button @click="handleLook(item)" class="commonBtnClass">
                    查看
                  </button>
                </view>
              </view>
            </view>
          </view>
          <view v-else class="loadingClass">暂无数据</view>
        </view>
      </view>
      <view v-if="current === 1"
        ><text class="content-text">
          <view class="tongji">
            <text class="commonClass">统计</text>
            <text @click="handleDetails(0)">详情</text>
          </view>
          <view class="charts-box">
            <qiun-data-charts
              type="arcbar"
              :opts="opts1"
              :chartData="chartData1"
            />
          </view>
          <view class="currentClass">
            <text>限量：100吨</text>
            <text>转运量:{{ allWeightval.toFixed(2) }}吨</text>
            <text style="color: red"
              >剩余量:{{ (100 - allWeightval).toFixed(2) }}吨</text
            >
          </view>
          <view class="tongji">
            <text class="commonClass">产出量统计</text>
            <text @click="handleDetails(1)">详情</text>
          </view>
          <view class="charts-box">
            <qiun-data-charts
              type="column"
              :opts="opts2"
              :chartData="chartData2"
              :ontouch="true"
            />
          </view> </text
      ></view>
    </view>
  </view>
</template>
  
  <script setup>
import qiunDataCharts from "@/uni_modules/qiun-data-charts/components/qiun-data-charts/qiun-data-charts";
import { useMemberStore } from "@/stores/modules/member";
import {
  get_my_task,
  get_my_forward_list,
  wfTypeFindPage,
  select_user_by_ids,
  select_depts_by_deptIds,
  select_trans_by_date_status,
} from "./index";
import { parseTime } from "@/utils";
const memberStore = useMemberStore();
const items = ref(["待办事项", "数据看板"]);
const current = ref(0);
const styleType = ref("button");
const activeColor = ref("#007aff");
const showHide = ref(false);
const titleName = ref("我的待办");
//我的待办
const state = reactive({
  rows: [],
});
//我的已办
const completedObj = reactive({
  rows: [],
});
onHide(() => {
  showHide.value = false;
  console.log(showHide.value, "onHide");
});
function dateTimeStringToTimestamp(dateTimeStr) {
  const [datePart, timePart] = dateTimeStr.split(" ");
  const [year, month, day] = datePart.split("-").map(Number);
  const [hour, minute, second] = timePart.split(":").map(Number);
  return new Date(year, month - 1, day, hour, minute, second).getTime();
}
function downOrder(lists) {
  lists.sort(
    (a, b) =>
      dateTimeStringToTimestamp(b.submitTime) -
      dateTimeStringToTimestamp(a.submitTime)
  );
}
onPullDownRefresh(async () => {
  await onRefresherrefresh();
  uni.stopPullDownRefresh();
});
const onRefresherrefresh = async () => {
  let res = null;
  try {
    res = await get_my_task();
  } catch (err) {
    res = await get_my_task();
  }
  state.rows = JSON.parse(JSON.stringify(res.data));
  const applyUserIds = state.rows.map((item) => item.applyUserId);
  const userIds = [...new Set(applyUserIds)].join();
  const promise1 = await select_user_by_ids(userIds);

  const applyDeptIds = state.rows.map((item) => item.applyDeptId);
  const depIds = [...new Set(applyDeptIds)].join();
  const promise2 = await select_depts_by_deptIds(depIds);
  const ress = await wfTypeFindPage();
  state.rows.forEach((item) => {
    item.submit_Time = parseTime(item.submitTime, "{y}-{m}-{d}");
    //获取危废行业俗称
    if (item.wfType) {
      const typeLists = item.wfType.split(",");
      const TypeNames = [];
      typeLists.forEach((wfType) => {
        const obj1 = ress.data.find((item) => item.id == wfType);
        if (obj1) {
          TypeNames.push(obj1.wfTypeName);
        }
      });
      item.wfTypeName = TypeNames.join(",");
    }
    //获取危废行业俗称
    const res1 = promise1.data.find((res) => res.userId == item.applyUserId);
    if (res1) {
      item.userName = res1.username;
    }
    const res2 = promise2.data.find((res) => res.deptId == item.applyDeptId);
    if (res2) {
      item.deptName = res2.name;
    }
    const lists = item.wfTransWeight ? JSON.parse(item.wfTransWeight) : [];
    item.wfTrans_Weight = lists.length
      ? lists.reduce((pre, next) => {
          if (next.wfWeight) {
            pre += +next.wfWeight;
          }
          return pre;
        }, 0)
      : "";
  });
  const result = await get_my_forward_list();
  completedObj.rows = JSON.parse(JSON.stringify(result.data));
  const applyUserIds1 = completedObj.rows.map((item) => item.applyUserId);
  const userIds1 = [...new Set(applyUserIds1)].join();
  const promise11 = await select_user_by_ids(userIds1);
  const applyDeptIds1 = completedObj.rows.map((item) => item.applyDeptId);
  const depIds1 = [...new Set(applyDeptIds1)].join();
  const promise21 = await select_depts_by_deptIds(depIds1);
  completedObj.rows.forEach((item) => {
    item.submit_Time = parseTime(item.submitTime, "{y}-{m}-{d}");
    //获取危废行业俗称
    if (item.wfType) {
      const typeLists = item.wfType.split(",");
      const TypeNames = [];
      typeLists.forEach((wfType) => {
        const obj1 = ress.data.find((item) => item.id == wfType);
        if (obj1) {
          TypeNames.push(obj1.wfTypeName);
        }
      });
      item.wfTypeName = TypeNames.join(",");
    }
    //获取危废行业俗称
    const res1 = promise11.data.find((res) => res.userId == item.applyUserId);
    if (res1) {
      item.userName = res1.username;
    }
    const res2 = promise21.data.find((res) => res.deptId == item.applyDeptId);
    if (res2) {
      item.deptName = res2.name;
    }
    const lists = item.wfTransWeight ? JSON.parse(item.wfTransWeight) : [];
    item.wfTrans_Weight = lists.length
      ? lists.reduce((pre, next) => {
          if (next.wfWeight) {
            pre += +next.wfWeight;
          }
          return pre;
        }, 0)
      : "";
  });
  downOrder(state.rows);
  downOrder(completedObj.rows);
  await selectByDate(ress);
  getServerData();
};

onShow(() => {
  onRefresherrefresh();
});
const onClickItem = (e) => {
  if (current.value !== e.currentIndex) {
    current.value = e.currentIndex;
  }
};

function handleAddLogin() {
  showHide.value = false;
  uni.navigateTo({
    url: "/pages/NewRegistration/NewRegistration",
  });
}
function handleApplication() {
  showHide.value = false;
  uni.navigateTo({
    url: "/pages/TransitApplication/TransitApplication",
  });
}
function handleshenpi(item) {
  memberStore.approval = JSON.parse(JSON.stringify(item));
  uni.navigateTo({
    url: `/pages/transportationInspection/transportationInspection`,
  });
}
function handleEdit(item) {
  memberStore.ApplyViewing = JSON.parse(JSON.stringify(item));
  uni.navigateTo({
    url: `/pages/ApplicationDetails/ApplicationDetails?fromPage=homePage`,
  });
}

const opts1 = ref({
  color: [
    "#1890FF",
    "#91CB74",
    "#FAC858",
    "#EE6666",
    "#73C0DE",
    "#3CA272",
    "#FC8452",
    "#9A60B4",
    "#ea7ccc",
  ],
  padding: undefined,
  title: {
    name: "1%",
    fontSize: 30,
    color: "rgb(0, 122, 255)",
  },
  subtitle: {
    name: "转运量",
    fontSize: 25,
    color: "#000",
  },
  extra: {
    arcbar: {
      type: "circle",
      width: 12,
      backgroundColor: "#E9E9E9",
      startAngle: 1.5,
      endAngle: 0.25,
      gap: 2,
    },
  },
});

const opts2 = ref({
  color: [
    "#1890FF",
    "#91CB74",
    "#FAC858",
    "#EE6666",
    "#73C0DE",
    "#3CA272",
    "#FC8452",
    "#9A60B4",
    "#ea7ccc",
  ],
  padding: [15, 15, 0, 5],
  touchMoveLimit: 24,
  enableScroll: true,
  legend: {},
  xAxis: {
    disableGrid: true,
    scrollShow: true,
    itemCount: 4,
  },
  yAxis: {
    data: [
      {
        min: 0,
      },
    ],
  },
  extra: {
    column: {
      type: "group",
      width: 30,
      activeBgColor: "#000000",
      activeBgOpacity: 0.08,
    },
  },
});

const chartData1 = ref({});
const chartData2 = ref({});
const allWeightval = ref(0);
const depObj = ref({});
const selectByDate = async (date) => {
  const res = await select_trans_by_date_status();
  depObj.value = res.data[0];
  for (const key in depObj.value) {
    depObj.value[key].forEach((item) => {
      const lists = item.wfTransWeight ? JSON.parse(item.wfTransWeight) : [];
      item.wfTypeWeight = lists.reduce((pre, next) => {
        if (next.wfWeight) {
          pre += +next.wfWeight;
        }
        return pre;
      }, 0);
      if (item.wfType) {
        const wfTypeLists = item.wfType.split(",");
        const TypeNames = [];
        wfTypeLists.forEach((wfType) => {
          const obj1 = date.data.find((item) => item.id == wfType);
          if (obj1) {
            TypeNames.push(obj1.wfTypeName);
          }
        });
        item.wfTypeName = TypeNames.join(",");
      }
    });
  }
  const tableLists = Object.values(depObj.value).flat(Infinity);
  //部门的数据
  allWeightval.value = tableLists.reduce((pre, next) => {
    if (next.wfTypeWeight) {
      pre += +next.wfTypeWeight;
    }
    return pre;
  }, 0);
};
const getServerData = () => {
  //产出量  100需要后端接口返回，后端还没做好这里暂时用100 就是限制量
  const weightPercentage = +(allWeightval.value / 100).toFixed(2);
  let res1 = {
    series: [
      {
        name: "转运量",
        color: "rgb(0, 122, 255)",
        data: weightPercentage,
      },
    ],
  };
  opts1.value.title.name = `${(weightPercentage * 100).toFixed(0)}%`;
  chartData1.value = JSON.parse(JSON.stringify(res1));
  const lists = Object.values(depObj.value);
  const dataWeight = lists.map((item) => {
    return item
      .reduce((pre, next) => {
        if (next.wfTypeWeight) {
          pre += +next.wfTypeWeight;
        }
        return pre;
      }, 0)
      .toFixed(2);
  });
  const categories = Object.keys(depObj.value);
  let res2 = {
    categories,
    series: [
      {
        name: "转运量(吨)",
        data: dataWeight,
      },
    ],
  };
  chartData2.value = JSON.parse(JSON.stringify(res2));
};
const handleDetails = (nub) => {
  memberStore.currentNub = nub;
  uni.switchTab({
    url: `/pages/search/search`,
  });
};
const handleLook = (item) => {
  memberStore.QueryTransferDetails = item;
  uni.navigateTo({
    url: `/pages/QueryTransferDetails/QueryTransferDetails`,
  });
};
const handleSearch = () => {
  uni.navigateTo({
    url: `/pages/searchPage/searchPage`,
  });
};
</script>
<style lang="scss" scoped>
.posiBox {
  display: flex;
  flex-direction: column;
  position: fixed;
  z-index: 11;
  top: 70rpx;
  right: 40rpx;
  padding: 20rpx;
  background-color: #eee;
  .common:hover {
    color: rgb(0, 122, 255);
  }
}
.content {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  .content-text {
    color: #666;
  }
}

.uni-padding-wrap {
  width: 50%;
}
.positionClass {
  color: rgb(0, 122, 255);
  display: flex;
  align-items: center;
  // 加搜索就把下面margin-left: 100rpx;注释了
  // margin-left: 100rpx;
}
.charts-box {
  width: 100%;
  margin-top: 30rpx;
  height: 300rpx;
}
.item {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40px;
  height: 40px;
  background-color: #ebebeb;
  border-radius: 10px;
  margin: 5px;
}
.boxTitle {
  padding: 10px 20px;
  display: flex;
  justify-content: space-around;
}
.yuanClass {
  box-sizing: border-box;
  text-align: center;
  background: red;
  color: #fff;
  border-radius: 2000rpx;
  padding: 0 0.5em;
  min-width: 60rpx;
  height: 60rpx;
  line-height: 60rpx;
  margin-left: 10rpx;
}
.flexClass {
  display: flex;
  box-sizing: border-box;
  background: #eee;
  padding: 5px 0;
  text {
    flex: 1;
    display: flex;
    align-items: center;
    text-align: center;
    justify-content: center;
  }
}
.white {
  background: white;
}
.titleClass {
  font-weight: bolder;
}
.currentClass {
  display: flex;
  justify-content: space-around;
  padding: 40rpx 0;
}
.tongji {
  display: flex;
  justify-content: space-between;
  padding: 20px;
}
.commonClass {
  font-size: 40rpx;
  font-weight: bold;
}
.headerClass {
  display: flex;
  justify-content: flex-end;
  padding-right: 34rpx;
  padding-top: 20rpx;
}
.icon-sousuo {
  color: rgb(0, 122, 255);
  font-size: 50rpx;
  margin: 0 20rpx;
}
</style>
  